from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.ext import db
import atom.url
import gdata.contacts.service
import gdata.alt.appengine
import settings
import cgi
import liveboarddb 
import logging


class Login(webapp.RequestHandler):
  
    def checkAuth(self):
        self.client = gdata.contacts.service.ContactsService()
        gdata.alt.appengine.run_on_appengine(self.client)
        try:
            uri = self.client.GetFeedUri()
            feed = self.client.GetContactsFeed(uri)
            return True
        except gdata.service.RequestError, request_error:
            return False


    def get(self):
        gid = self.request.get('gid')
        
        user = users.get_current_user()
        if not user:
          if gid:
              path = "/auth?gid=%s" % gid
          else:
              path = "/auth"
          next_url = atom.url.Url('http', settings.HOST_NAME, path=path)
          self.response.out.write("Not logged in ")
          self.response.out.write('<a href="%s" class="ui-btn-right" data-role="button">Sign In</a>' % (
            users.create_login_url(str(next_url))))
          
        else:
          self.response.out.write("Hello, %s " % user.nickname())
          #if self.checkAuth():
          if gid:
              path = "/index.html?gid=%s" % gid
          else:
              path = "/index.html"
          next_url = atom.url.Url('http', settings.HOST_NAME, path=path)
          self.response.out.write('<a href="%s" class="ui-widget">Sign Out</a>' % (
            users.create_logout_url(str(next_url))))
          #else:
          #    if gid:
          #        path = "/auth?gid=%s" % gid
          #    else:
          #        path = "/auth"
          #    next_url = atom.url.Url('http', settings.HOST_NAME, path=path)
          #    auth_uri = self.client.GenerateAuthSubURL(next_url,
          #    ('http://docs.google.com/feeds/','http://www.google.com/m8/feeds',), secure=False, session=True)
          #    self.response.out.write('<a href="%s" class="ui-widget">Authorize</a>' % (
          #      users.create_logout_url(str(auth_uri))))

          #save in the db
          q = db.GqlQuery("SELECT * FROM UserInfo WHERE email = :1", user.email())
          r = q.fetch(1)

          if len(r) == 1:
            ui = r[0]
          else:
            ui = liveboarddb.UserInfo()

          ui.user = user
          ui.uid = 0
          ui.name = user.nickname()
          ui.email = user.email()
          db.put(ui)

def main():
    application = webapp.WSGIApplication([('/login', Login), ], debug=True)
    run_wsgi_app(application)

if __name__ == '__main__':
    main()
